package juc.future;

import java.util.concurrent.*;

/**
 * @author fangbin
 * @desc 演示get的超时方法，需要注意超时后处理，调用future.cancle().
 * 演示cancle传入true和false的区别，代表是否中断正在执行的任务
 * @date 2020/6/30 20:57
 */
public class Timeout {

    private static final ExecutorService exec =
            Executors.newFixedThreadPool(10);
    static class Ad{
        private String name;
        public Ad(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Ad{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    static class FetchAdTask implements Callable<Ad>{
        @Override
        public Ad call() throws Exception {
            try {
                Thread.sleep(3000);
            }catch (InterruptedException e){
                System.out.println("sleep期间被中断了");
                return new Ad("被中断时的默认广告");
            }
            return new Ad("网上订票哪家强，上某程");
        }
    }

    public void printAd(){
        Ad ad=null;
        Future<Ad> f =  exec.submit(new FetchAdTask());
        try {
          ad =   f.get(2000,TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            ad = new Ad("被中断时的默认广告");
            e.printStackTrace();
        } catch (ExecutionException e) {
            ad = new Ad("异常时候的的默认广告");
            e.printStackTrace();
        } catch (TimeoutException e) {
            ad = new Ad("超时时候的默认广告");
            System.out.println("超时，为获取到广告");
            boolean cancle = f.cancel(true);
            System.out.println("cancle的结果："+cancle);

        }
        exec.shutdown();
        System.out.println(ad);
    }

    public static void main(String[] args) {
        Timeout timeout = new Timeout();
        timeout.printAd();
    }
}
